package com.murphy.algorithm.linked;

import com.alibaba.fastjson.JSON;

/**
 *
 * @author dongsufeng
 * @date 2020/9/4 17:35
 * @version 1.0
 */
public class MyLinkedList<E> {

    public static class Node<E> {
        public Node<E> pre;
        public E e;

        public Node<E> next;

        Node(Node<E> pre,E e,Node<E> next){
            this.pre=pre;
            this.e=e;
            this.next=next;
        }
    }
    private Node<E> first;
    private Node<E> last;
    public void add(E e){
        Node<E> oNode=last;
        //默认追加末尾
        Node<E> newNode = new Node<>(last,e,null);
        last = newNode;
        if (oNode==null){
            first = newNode;
        }else {
            oNode.next = newNode;
        }
    }
    public Node<E> revers(Node<E> node){

        Node<E> pre = null;
        Node<E> next = null;
        while (node!=null){
            //取出第二个node
            next = node.next;
            //将第一个node的next指针指向上一个node，此时该node处于新链表的头
            node.next = pre;
            //所以将头设为空
            node.pre = null;
            //如果还有下一个，就将下一个的pre指针指向自己（双向链表）
            if (node.next != null){
                node.next.pre = node;
            }
            //把最新node（头）赋值pre为下一次循环使用
            pre = node;
            //将下一个node设为当前node继续下次循环
            node = next;
            //期间会新建一个链表，新链表不断增长，旧链表不断缩短
        }
        return pre;
    }
    public static void main(String[] args) {
        MyLinkedList<String> myLinkedList = new MyLinkedList<>();
        myLinkedList.add("111");
        myLinkedList.add("222");
        myLinkedList.add("333");
        myLinkedList.add("444");
        myLinkedList.add("555");
        System.out.println(myLinkedList.first.e);
        Node<String> revers = myLinkedList.revers(myLinkedList.first);
        System.out.println(revers.e);
    }

}
